package be.webchess.www.dao;

import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;
import java.util.LinkedList;
import java.util.List;

import be.webchess.www.model.Room;
import be.webchess.www.model.User;

public class RoomDAO extends GenericDAO<Room> {

	ConnectedUsersDAO		cuDAO;
	
	public RoomDAO(Connection c) {
		super(c);
		
		cuDAO = new ConnectedUsersDAO(c);
	}

	@Override
	public Room findByID(Long id) throws SQLException {
		Room room = null;
		
		StringBuffer query = new StringBuffer();
		query.append("SELECT ");
		query.append("r.id, ");
		query.append("r.name, ");
		query.append("r.flags ");
		query.append("FROM room r ");
//		query.append("INNER JOIN connected_users c on r.id=c.id_room ");
		query.append("WHERE r.id=?");
		
		PreparedStatement stmt = con.prepareStatement(query.toString());
		stmt.setLong(1, id);

		ResultSet result = stmt.executeQuery();
		if(result.next()) {
			room = new Room();
			buildObject(result, room);
		}
		
		room.setConnectedUsers(cuDAO.findUsers(room));
		
		return room;
	}

	@Override
	public Room insert(Room o) throws SQLException {
		StringBuffer query = new StringBuffer();
		query.append("INSERT INTO room(");
		query.append("name, ");
		query.append("flags, ");
		query.append(") VALUES (?,?)");
//		query.append("INNER JOIN users u on u.idUsers=a.idUser ");
//		query.append("WHERE u.id=?");
		
		PreparedStatement stmt = con.prepareStatement(query.toString());
		stmt.setString(1, o.getName());
		stmt.setLong(2, o.getFlags());

		stmt.executeUpdate();

		ResultSet result = stmt.getGeneratedKeys();
		
		if(result.next()) {
			o.setId(result.getLong("id"));
		}
		
		
		return o;
	}

	@Override
	public Room update(Room o) throws SQLException {
		// TODO Auto-generated method stub
		return null;
	}

	@Override
	public void delete(Room o) throws SQLException {
		// TODO Auto-generated method stub
		
	}

	@Override
	public List<Room> findAll() throws SQLException {
		// TODO Auto-generated method stub
		return null;
	}

	static void buildObject(ResultSet result, Room room) throws SQLException{
		int		col = 1;
		
		room.setId(result.getLong(col++));
		room.setName(result.getString(col++));
		room.setFlags(result.getLong(col++));
	}

}
